const express = require('express')
const router = express.Router()
const db = require('../db.js')
const moment = require('moment')

//导入生成token字符串的包
const jwt = require('jsonwebtoken')
//导入token的密钥配置文件
const config = require('../config')

//导入bcryptjs 用于对密码加密，加密后无法被逆向破解噢
const bcrypt = require('bcryptjs')
//1.导入验证表单数据的中间件
const expressJoi = require('@escook/express-joi')
//2.导入需要的验证规则对象
const { reg_login_schema } = require('../schema/user')
const { json } = require('express')

// 查询用户列表,page页码,row每页几条数据,keyword查询用户名字,order年龄升序asc和降序desc
router.get("/list", (req, res) => {
	const page = parseInt(req.query.page || 1)
	const row = parseInt(req.query.row || 10)
	const keyword = req.query.keyword || ''
	const sort = req.query.sort || 'user_id'
	const order = req.query.order || 'asc'
	const params = ['%' + keyword + '%',sort, (page - 1)*row, row]
	db.query("select * from user where username like ? order by ? " + order + " limit ?,?", params, (err,result) => {
			if (err) {
				throw new Error(err)
			} else {
				db.query('select count(*) as records from user where username like ?', '%' + keyword + '%',(error, results) => {
					if (error) {
						throw new Error(error)
					} else {
						for(let i in result){
							result[i].birthday=moment(result[i].birthday).format('YYYY-MM-DD')
							result[i].create_time=moment(result[i].create_time).format('YYYY-MM-DD')
							result[i].login_time=moment(result[i].login_time).format('YYYY-MM-DD HH:mm:ss')
							delete result[i].password
						}
						res.json({
							code: 200,
							msg: "ok",
							data: result,
							page: page,
							row: row,
							records: results[0]['records'],
							total:  Math.ceil(results[0]['records']/row)
						})
					}
				})
			}
		})
})

//查询某个用户信息
router.get("/person", (req, res) => {
	db.query('select * from user where user_id = ?', req.query.user_id, (err, result) => {
		if (err) {
			throw new Error(err)
		} else {
			if (!result[0]) {
				res.json({
					code: 250,
					msg: "用户不存在"
				})
			} else {
        console.log('result[0]',result[0])
				delete result[0].password
        if(result[0].birthday == null){
          result[0].birthday=moment().format('YYYY-MM-DD')
        }
        const imgName = result[0].face.split('/')
        result[0].face = global.baseUrl + "/assets/uploads/" + imgName[imgName.length - 1]
        result[0].login_time = moment(result[0].login_time).format('YYYY-MM-DD HH:mm:ss')
        result[0].create_time = moment(result[0].create_time).format('YYYY-MM-DD HH:mm:ss')
				// result[0].birthday=moment(result[0].birthday).format('YYYY-MM-DD')
				res.json({
					code: 200,
					msg: 'ok',
					data: result[0]
				})
			}
		}
	})
})


//用户登录
// router.post("/login", (req, res) => {
// 	if (!req.body.name) {
// 		throw new Error('请填写账号')
// 	}else if (!req.body.password) {
// 		throw new Error('请填写密码')
// 	}else{
// 		db.query('select * from user where name = ?', req.body.name, (err, result) => {
// 			if (err) {
// 				throw new Error(err)
// 			} else {
// 				if (result[0]) {
// 					if (req.body.password == result[0].password) {
// 						if(result[0].status==1){
// 							db.query("update user set login_time = ? where name = ?", [moment().valueOf(),req.body.name],(err, results) => {
// 								result[0].login_time=moment().valueOf()
// 								result[0].birthday=moment().format('YYYY-MM-DD')
// 								res.json({
// 									code: 200,
// 									msg: '登录成功',
// 									data: result[0]
// 								})
// 							})
// 						}else{
// 							res.json({
// 								code: 250,
// 								msg: '你已被封号,请联系管理员!'
// 							})
// 						}
// 					} else {
// 						res.json({
// 							code: 250,
// 							msg: "密码错误"
// 						})
// 					}
// 				} else {
// 					res.json({
// 						code: 250,
// 						msg: "账号不存在"
// 					})
// 				}
// 			}
// 		})
// 	}
// })

//用户注册2
router.post('/add',expressJoi(reg_login_schema),(req,res)=>{
  //判断用户名是否存在
  db.query('select * from user where username=?',req.body.username,(err,result)=>{
    if(err){ return res.json({code:250,msg:err}) }
    if(result.length > 0){ return res.json({code:250,msg:'用户名已存在，请换其他用户名！'}) }
    //用户名可用，则继续流程,先存一份用户名和密码到password仓库
    const info = { username:req.body.username, password:req.body.password }
    db.query('insert into password set ?',info,(err,result)=>{
      if(err){ return res.json({ code:250,msg:err }) }
    })
    
    //对密码进行加密
    req.body.password = bcrypt.hashSync(req.body.password,10)
    // console.log('2',req.body)
    db.query("select * from sys", (err, result) => {
      req.body.face=result[1].avatar
      req.body.create_time = moment().valueOf()
      req.body.login_time=moment().valueOf()
      req.body.nickName=req.body.username
      //将注册信息插入数据库
      db.query("insert into user set ?", req.body, (err, result) => {
        if(err){ return res.json({code:250,msg:err}) }
        if(result.affectedRows !== 1){ return res.json({code:250,msg:'注册失败，请稍后再试'}) }
        db.query('select * from user where username = ?', req.body.username, (err, result) => {
          if(err){ return res.json({ code:250,msg:err }) }
          //格式化生日时间
          result[0].birthday=moment().format('YYYY-MM-DD')
          res.json({code:200, message:'注册成功！'})
        })
      })
    })
  })
})
//用户登录2
router.post('/login',expressJoi(reg_login_schema),(req,res)=>{
  const userinfo = req.body
  db.query('select * from user where username = ?',userinfo.username,(err,results)=>{
    if(err) return res.json({code:250,msg:err})
    if(results.length !== 1) return res.json({code:250,msg:'账号或密码错误！'})
    
    const compareResult = bcrypt.compareSync(userinfo.password,results[0].password)
    if(!compareResult){ return res.json({ code:250,msg:'账号或密码错误！' })}
    //status: 1=>正常状态  2=>封号状态
    if(results[0].status==2){ return res.json({ code:250,msg:'你已被封号,请联系管理员!' })}
    //登录成功，更新头像真实地址
    const imgName = results[0].face.split('/')
    results[0].face = global.baseUrl + "/assets/uploads/" + imgName[imgName.length - 1]
    //将password这个属性清空
    const user = { ...results[0], password:'',}
    //生成token
    const tokenStr = jwt.sign(user,config.jwtSecretKey,{ expiresIn:'48h' })
    user.token = tokenStr
    //更新登录时间
    db.query("update user set login_time = ? where username = ?", [moment().valueOf(),req.body.username],(err, result) => {
      if(err) return res.json({code:250,msg:err})
      //调整好格式再返回
      user.login_time =  moment().format('YYYY-MM-DD HH:mm:ss')
      res.json({
        code: 200,
        msg: '登录成功',
        data: user
      })
    })
  })
})

//验证是否为超级管理员
router.get('/isAdmin',(req,res)=>{
  db.query('select * from user where user_id = ?', req.query.user_id,(err,result)=>{
    if(err) return res.json({code:250,msg:err})
    if(result.length == 1){
      res.json({
        code:200,
        msg:'ok',
        data:result[0].is_admin
      })
    }
  })
})


// 用户注册
// router.post("/add", (req, res) => {
// 	if (!req.body.name) {
// 		throw new Error('请填写账号')
// 	} else if (!req.body.password) {
// 		throw new Error('请填写密码')
// 	} else if (req.body.password.length<6||req.body.password.length>18) {
// 		throw new Error('密码长度6-18位')
// 	}else {
// 		db.query('select * from user where name = ?', req.body.name, (err, result) => {
// 			if (result[0]) {
// 				res.json({
// 					code: 250,
// 					msg: "账号已存在"
// 				})
// 			} else {
// 				db.query("select * from sys", (err, result) => {
// 					req.body.face=result[0].avatar
// 					req.body.create_time = moment().valueOf()
// 					req.body.login_time=moment().valueOf()
// 					req.body.nickName=req.body.name
// 					db.query("insert into user set ?", req.body, (err, result) => {
// 						if (err) {
// 							throw new Error(err)
// 						} else {
// 							db.query('select * from user where name = ?', req.body.name, (err, result) => {
// 								delete result[0].password
// 								result[0].birthday=moment(result[0].birthday).format('YYYY-MM-DD')
// 								res.json({
// 									code: 200,
// 									msg: 'ok',
// 									data: result[0]
// 								})
// 							})
// 						}
// 					})
// 				})
// 			}
// 		})
// 	}
// })

// 用户注销
router.post("/delete", (req, res) => {
  return console.log(req.body)
	if(!req.body.per_id){
		throw new Error('请登录')
	}else{
		delete req.body.per_id
		db.query("delete from user where user_id = ?", req.body.user_id, (err, result) => {
			if (err) {
				throw new Error(err)
			} else {
				res.json({
					code: 200,
					msg: 'ok'
				})
			}
		})
	}
})

// 修改用户信息
router.post('/edit', (req, res) => {
	// if(!req.body.per_id){
	// 	throw new Error('请登录')
	// }else if (!req.body.user_id) {
	// 	throw new Error('用户信息有误')
	// } else {
	// 	delete req.body.per_id
  console.log('edit',req.body)
		db.query('update user set ? where user_id=?', [req.body, req.body.user_id], (err, results) => {
			if (err) {
				throw new Error(err)
			} else {
				db.query('select * from user where user_id = ?', req.body.user_id, (err, results) => {
					if (err) {
						throw new Error(err)
					} else {
						// delete results[0].password
						results[0].birthday=moment(results[0].birthday).format('YYYY-MM-DD')
						res.json({
							code: 200,
							msg: '修改成功',
							data: results[0]
						})
					}
				})
			}
		})
	//}
})

module.exports = router